package cn.kent.nio.byteBuffer;


import java.nio.ByteBuffer;

import static cn.kent.nio.byteBuffer.util.ByteBufferUtil.debugAll;

/**
 * 处理黏包，半包问题
 * 问题引出：
 * "Who are you?\n"
 * "I am zhangsan.\n"
 * "How are you?\n"
 * -  黏包："Who are you?\nI am zhangsan.\nHow are you?\n"
 * -  半包: "Who are you?\nI am zhan"
 * "gsan.\nHow are you?\n"
 * 黏包半包把所有内存空间压缩了，更高效， 处理的时候遍历每一个字符判断是否是\n然后进行截断即可
 */
public class TestByteBufferExam {

    public static void main(String[] args) {
        ByteBuffer b = ByteBuffer.allocate(64);
        b.put("Who are you?\nI am zhan".getBytes());
        split(b);
        b.put("gsan.\nHow are you?\n".getBytes());
        split(b);
    }

    private static void split(ByteBuffer source) {
        source.flip();
        for (int i = 0; i < source.limit(); i++) {
            if (source.get(i) == '\n') {
                int length = i + 1 - source.position(); // 保留 \n 字符
                ByteBuffer target = ByteBuffer.allocate(length);
                for (int j = 0; j < length; j++) {
                    target.put(source.get());
                }
                debugAll(target);
            }
        }
        source.compact();
    }
}
